#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
腾讯云HAI配置验证工具
快速验证当前配置是否正确
"""

import os
import sys
import json
from pathlib import Path
from typing import Dict, Any

def load_env_config() -> Dict[str, str]:
    """加载环境配置"""
    env_file = Path(__file__).parent / ".env"
    config = {}
    
    if env_file.exists():
        with open(env_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    config[key] = value
    else:
        print("❌ 未找到 .env 配置文件")
        print("请先运行: python3 setup_security.py")
        return {}
    
    return config

def check_required_config(config: Dict[str, str]) -> bool:
    """检查必需配置"""
    required_keys = ['TENCENT_SECRET_ID', 'TENCENT_SECRET_KEY', 'TENCENT_REGION']
    missing_keys = []
    
    for key in required_keys:
        if key not in config or not config[key] or config[key].startswith('your_'):
            missing_keys.append(key)
    
    if missing_keys:
        print(f"❌ 缺少必需配置: {', '.join(missing_keys)}")
        return False
    
    print("✅ 必需配置检查通过")
    return True

def test_api_connection(config: Dict[str, str]) -> bool:
    """测试API连接"""
    try:
        # 设置环境变量
        os.environ.update(config)
        
        # 导入并测试HAI客户端
        sys.path.insert(0, str(Path(__file__).parent))
        from core.tencent_hai_api import TencentHAIClient
        
        print("🔗 测试API连接...")
        client = TencentHAIClient(
            config["TENCENT_SECRET_ID"],
            config["TENCENT_SECRET_KEY"],
            config["TENCENT_REGION"]
        )
        
        if client.enabled:
            print("✅ API连接成功")
            print(f"   地域: {config['TENCENT_REGION']}")
            print(f"   真实应用: {len(client.real_apps)} 个")
            
            # 获取真实应用状态
            real_apps_status = client.get_real_apps_status()
            if "error" not in real_apps_status:
                print(f"   健康应用: {real_apps_status.get('healthy_apps', 0)}/{real_apps_status.get('total_apps', 0)}")
            
            return True
        else:
            print("❌ API连接失败")
            return False
            
    except Exception as e:
        print(f"❌ API连接测试失败: {e}")
        return False

def test_real_apps() -> bool:
    """测试真实应用功能"""
    try:
        print("🧪 测试真实应用功能...")
        
        # 运行真实应用测试
        import subprocess
        result = subprocess.run([
            sys.executable, "test_real_apps.py"
        ], capture_output=True, text=True, cwd=Path(__file__).parent)
        
        if result.returncode == 0:
            print("✅ 真实应用测试通过")
            return True
        else:
            print("❌ 真实应用测试失败")
            if result.stderr:
                print(f"错误信息: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ 真实应用测试失败: {e}")
        return False

def show_system_status():
    """显示系统状态"""
    try:
        print("\n📊 系统状态")
        print("-" * 40)
        
        # 导入控制器
        sys.path.insert(0, str(Path(__file__).parent))
        from core.tencent_hai_api import TencentHAIClient
        
        # 创建客户端
        config = load_env_config()
        if not config:
            return
            
        client = TencentHAIClient(
            config["TENCENT_SECRET_ID"],
            config["TENCENT_SECRET_KEY"],
            config["TENCENT_REGION"]
        )
        
        # 获取系统统计
        stats = client.get_system_statistics()
        
        print("真实应用状态:")
        real_apps = stats.get('real_apps', {})
        if "error" not in real_apps:
            print(f"  总应用数: {real_apps.get('total_apps', 0)}")
            print(f"  健康应用数: {real_apps.get('healthy_apps', 0)}")
            print(f"  健康率: {real_apps.get('health_rate', 0):.1%}")
            
            print("  地域分布:")
            region_stats = real_apps.get('region_statistics', {})
            for region, region_info in region_stats.items():
                if region_info['total'] > 0:
                    print(f"    {region}: {region_info['healthy']}/{region_info['total']} 健康")
        else:
            print(f"  错误: {real_apps['error']}")
        
        # 显示模拟实例状态
        simulated = stats.get('simulated_instances', {})
        print(f"\n模拟实例状态:")
        print(f"  总实例数: {simulated.get('total_instances', 0)}")
        print(f"  运行实例数: {simulated.get('running_instances', 0)}")
        print(f"  每小时成本: ¥{simulated.get('total_hourly_cost', 0):.2f}")
        
    except Exception as e:
        print(f"❌ 获取系统状态失败: {e}")

def main():
    """主函数"""
    print("🔍 腾讯云HAI配置验证工具")
    print("=" * 40)
    
    # 加载配置
    config = load_env_config()
    if not config:
        return False
    
    # 检查必需配置
    if not check_required_config(config):
        return False
    
    # 测试API连接
    if not test_api_connection(config):
        return False
    
    # 测试真实应用
    if not test_real_apps():
        print("⚠️  真实应用测试失败，但基本配置可用")
    
    # 显示系统状态
    show_system_status()
    
    print("\n🎉 配置验证完成！")
    print("\n📋 后续操作:")
    print("  - 启动系统: python3 start.py")
    print("  - 查看API: http://localhost:8080/api/v1/real-apps/status")
    print("  - 重新配置: python3 setup_security.py")
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
